package org.netspeak.android.app;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.netspeak.android.utils.LittleHelper;
import org.netspeak.android.utils.ParcelablePhrase;
import org.netspeak.application.ErrorCode;
import org.netspeak.application.generated.NetspeakMessages.Phrase;
import org.netspeak.application.generated.NetspeakMessages.Response;
import org.netspeak.client.Netspeak;
import org.netspeak.client.Request;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * {@link AsyncTask} extension that sends a {@link Request} to Netspeak 
 * server and receives a list of {@link Phrase} as response.
 *
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class NetspeakRequestTask extends AsyncTask<String, Void, List<Phrase>> {
    
    private static final String TAG = "NetspeakRequestTask";
    private Netspeak mNetspeak = new Netspeak();
    private ProgressDialog mProgressDialog;
    private Context mContext;
    private long mTotalFrequency = 0;
    private String mQuery = "";
    
    public NetspeakRequestTask(Context context) {
        mContext = context;
    }
        
    @Override
    protected void onPreExecute() {
        // create and show indeterminate ProgressDialog
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setTitle("Contacting Netspeak...");
        mProgressDialog.setMessage("Please wait.");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
    }

    @Override
    protected List<Phrase> doInBackground(String... params) {
        List<Phrase> results = new ArrayList<Phrase>();
        for (String param : params) {
            mQuery = param;
            // create request
            Request request = new Request(); 
            request.put(Request.QUERY, param);
            request.put(Request.TOPK, String.valueOf(100)); 
            try {
                // send request, receive response
                Response response = mNetspeak.search(request);
                ErrorCode errorCode = ErrorCode.cast(response
                        .getErrorCode());
                // check for errors
                if (errorCode != ErrorCode.NO_ERROR) {
                    // log error
                    Log.w(TAG, "Netspeak error code: " + errorCode);
                    Log.w(TAG, "Netspeak error message: "
                                    + response.getErrorMessage());
                    // show error message as Toast
                    showToast(response.getErrorMessage());
                }
                // add results to returned list
                results.addAll(response.getPhraseList());
                mTotalFrequency = response.getTotalFrequency();
            } catch (MalformedURLException e) {
                Log.e(TAG, e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }            
        return results;
    }

    @Override
    protected void onPostExecute(List<Phrase> results) {
        // start Intent with same Activity
        Intent intent = new Intent(mContext, NetspeakActivity.class);
        // we cannot send Objects in an intent, so we have to convert it 
        // into Parcelable Objects
        ArrayList<ParcelablePhrase> parcelablePhrases = LittleHelper
                .convertToParcelable(results);
        intent.putParcelableArrayListExtra(NetspeakActivity.PHRASES, 
                parcelablePhrases);
        intent.putExtra(NetspeakActivity.FREQUENCY, mTotalFrequency);
        intent.putExtra(NetspeakActivity.QUERY, mQuery);
        mContext.startActivity(intent);
        // now all work is done, so dismiss the ProgressDialog
        mProgressDialog.dismiss();
    }
    
    /**
     * Shows a {@link Toast} with given text.
     * 
     * @param text  the text to display as Toast
     */
    private void showToast(String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
    }
}
